package cn.tutu.blockchain.sysuser.service.impl;

import java.util.List;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.tutu.blockchain.common.Page;
import cn.tutu.blockchain.exception.BusinessException;
import cn.tutu.blockchain.sysuser.dao.SysRoleDao;
import cn.tutu.blockchain.sysuser.dao.SysUserDao;
import cn.tutu.blockchain.sysuser.dao.SysUserRoleRefDao;
import cn.tutu.blockchain.sysuser.entity.SysRole;
import cn.tutu.blockchain.sysuser.entity.SysUser;
import cn.tutu.blockchain.sysuser.entity.SysUserRoleRef;
import cn.tutu.blockchain.sysuser.service.SysUserService;
import cn.tutu.blockchain.utils.MsgUtils;

@Service
public class SysUserServiceImpl implements SysUserService {

	@Autowired
	private SysUserDao sysUserDao;

	@Autowired
	private SysRoleDao sysRoleDao;

	@Autowired
	private SysUserRoleRefDao sysUserRoleRefDao;

	@Value("${cn.tutu.blockchain.newuser.roleid}")
	private String newUserRole;

	@Override
	public SysUser findByPhone(String phone) {
		SysUser sysuser = sysUserDao.findByPhone(phone);
		if (null != sysuser) {
			SysRole role = sysRoleDao.findByUserId(sysuser.getId());
			sysuser.setRole(role);
		}
		return sysuser;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 30000, rollbackFor = Exception.class)
	public void create(SysUser sysuser) {
		// Session session = SecurityUtils.getSubject().getSession();
		String code = MsgUtils.map.get(sysuser.getPhone());
		// String code = (String) session.getAttribute(sysuser.getPhone());
		// code = "123456";
		if (StringUtils.isEmpty(code) || !code.equals(sysuser.getVerificationCode())) {
			throw new BusinessException("验证码错误");
		}
		// 校验手机号是否已注册
		MsgUtils.map.remove(sysuser.getPhone());
		SysUser user = sysUserDao.findByPhone(sysuser.getPhone());
		if (null != user) {
			throw new BusinessException("手机号已注册");
		}
		if (!StringUtils.isEmpty(sysuser.getReferrerPhone())) {
			SysUser refUser = sysUserDao.findByPhone(sysuser.getReferrerPhone());
			if (refUser == null) {
				throw new BusinessException("推荐人手机号不存在");
			}
		}

		if (StringUtils.isEmpty(sysuser.getNickName())) {
			sysuser.setNickName(sysuser.getPhone());
		}
		// TODO
		// 密码加密
		Object result = new SimpleHash("MD5", sysuser.getPassword(),
				ByteSource.Util.bytes(sysuser.getPhone().getBytes()), 5);

		sysuser.setPassword(result.toString());
		// sysuser.setNickName(sysuser.getPhone());
		sysuser.setIntegral(0.0);
		sysuser.setTransactionPwd(result.toString());
		sysUserDao.insert(sysuser);

		// 设置新用户角色
		SysUserRoleRef sysUserRoleRef = new SysUserRoleRef(sysuser.getId(), newUserRole);
		sysUserRoleRefDao.insert(sysUserRoleRef);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 30000, rollbackFor = Exception.class)
	public void update(SysUser sysUser) {
		sysUserDao.update(sysUser);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 30000, rollbackFor = Exception.class)
	public void updateLoginStatus(SysUser sysuser) {
		// TODO Auto-generated method stub
		sysUserDao.updateLoginStatus(sysuser);

	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 30000, rollbackFor = Exception.class)
	public void updatePwd(SysUser sysuser, String oldPwd) {

		// Session session = SecurityUtils.getSubject().getSession();
		// String code = (String) session.getAttribute(sysuser.getPhone());
		// code = "123456";
		String code = MsgUtils.map.get(sysuser.getPhone());
		if (StringUtils.isEmpty(code) || !code.equals(sysuser.getVerificationCode())) {
			throw new BusinessException("验证码错误");
		}

		MsgUtils.map.remove(sysuser.getPhone());
		String hashOldPwd = new SimpleHash("MD5", oldPwd, ByteSource.Util.bytes(sysuser.getPhone().getBytes()), 5) + "";
		SysUser user = sysUserDao.findByPhone(sysuser.getPhone());

		if (!hashOldPwd.equals(user.getPassword())) {
			throw new BusinessException("旧密码错误");
		}

		// 密码加密
		Object result = new SimpleHash("MD5", sysuser.getPassword(),
				ByteSource.Util.bytes(sysuser.getPhone().getBytes()), 5);

		sysuser.setPassword(result.toString());
		sysUserDao.updatePwd(sysuser);
	}

	@Override
	public void resetPwd(SysUser sysuser) {
		SysUser user = sysUserDao.findByPhone(sysuser.getPhone());

		if (null == user) {
			throw new BusinessException("用户不存在!");
		}
		// Session session = SecurityUtils.getSubject().getSession();
		// String code = (String) session.getAttribute(sysuser.getPhone());
		String code = MsgUtils.map.get(sysuser.getPhone());

		if (StringUtils.isEmpty(code) || !code.equals(sysuser.getVerificationCode())) {
			throw new BusinessException("验证码错误!");
		}
		MsgUtils.map.remove(sysuser.getPhone());
		// 密码加密
		Object result = new SimpleHash("MD5", sysuser.getPassword(),
				ByteSource.Util.bytes(sysuser.getPhone().getBytes()), 5);

		sysuser.setPassword(result.toString());
		sysUserDao.updatePwdByPhone(sysuser);

	}

	@Override
	public SysUser getUserById(String id) {
		return sysUserDao.findById(id);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 30000, rollbackFor = Exception.class)
	public void removeByPhone(String phone) {
		sysUserDao.deleteByPhone(phone);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 30000, rollbackFor = Exception.class)
	public void modifyEthIdByPhone(String phone, String ethId) {
		sysUserDao.updateEthIdByPhone(phone, ethId);
	}

	@Override
	public PageInfo<SysUser> getByRefPhone(String refPhone, Page page) {
		PageHelper.startPage(page.getPageNum(), page.getPageSize());
		List<SysUser> list = sysUserDao.findByRefPhone(refPhone);
		PageInfo<SysUser> pageInfo = new PageInfo<SysUser>(list);
		return pageInfo;
	}

	@Override
	public SysUser getById(String userId) {

		return sysUserDao.findById(userId);
	}

	@Override
	public List<SysUser> getAll() {
		// TODO Auto-generated method stub
		return sysUserDao.findAll();
	}

}
